package com.ruoyi.sms.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.sms.service.ISmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class SmsController {

    @Autowired
    private ISmsService smsService;
    @Autowired
    private RedisService redisService;

    /**
     * 通过短信向物业公司发送 后台管理系统账号
     * @return
     */
    @GetMapping("/sendRealtySystemAccount")
    public R sendRealtySystemAccount(@RequestParam("tel") String tel,@RequestParam("username") String username, @RequestParam("password") String password){
        boolean flag = smsService.sendRealtySystemAccount(tel,username,password);
        if(flag){
            return R.ok();
        }
        return R.fail();
    }

    @GetMapping("sendVerificationCode")
    public R sendVerificationCode(String tel){
        String code = RandomUtil.randomNumbers(4);
        boolean flag = smsService.sendVerificationCode(tel,code);
        if(flag){
            redisService.setCacheObject("verificationCode_"+tel,code,300L, TimeUnit.SECONDS);
            return R.ok();
        }
        return R.fail();
    }

    @GetMapping("checkVerificationCode")
    public R<Boolean> checkVerificationCode(String tel,String code){
        String redisCode = redisService.getCacheObject("verificationCode_"+tel);
        if(StrUtil.isEmpty(redisCode)){
            return R.ok(false);
        }
        if(redisCode.equals(code)){
            return R.ok(true);
        }else {
            return R.ok(false);
        }
    }

}
